package net.xdclass.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.model.LoginUser;

import java.util.Date;

@Slf4j
public class JWTUtil {
    /**
     * 主题
     */
    private static final String SUBJECT = "xdclass";

    /**
     * 主题
     */
    private static final String SECRET = "xdclass.net168";
    /**
     * 主题
     */
    private static final String  TOKEN_PREFIX= "dcloud-link";
    /**
     * 主题
     */
    private static final long EXPIRE = 1000 * 60 * 60 *24 * 7;
    /**
     * 根据用户信息，生成令牌
     *
     * @param user
     * @return
     */
    public static String geneJsonWebToken(LoginUser user) {

        if (user == null) {
            throw new NullPointerException("对象为空");
        }

        String token = Jwts.builder().setSubject(SUBJECT)
                .claim("head_img", user.getHeadImg())
                .claim("account_no", user.getAccountNo())
                .claim("username", user.getUsername())
                .claim("mail",user.getMail())
                .claim("phone", user.getPhone())
                .claim("auth",user.getAuth())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, SECRET).compact();

        token = TOKEN_PREFIX + token;

        return token;
    }

    /**
     * 校验token的方法
     *
     * @param token
     * @return
     */
    public static Claims checkJWT(String token) {

        try {

            final Claims claims = Jwts.parser().setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(TOKEN_PREFIX, "")).getBody();

            return claims;

        } catch (Exception e) {
            log.info("解密异常");
            return null;
        }

    }
}
